// 统一用户数据管理工具
class UserDataManager {
  constructor() {
    this.storageKey = 'user';
    this.listeners = []; // 数据变化监听器
  }

  // 获取用户数据
  getUserData() {
    try {
      return wx.getStorageSync(this.storageKey) || this.getDefaultData();
    } catch (e) {
      console.error('获取用户数据失败:', e);
      return this.getDefaultData();
    }
  }

  // 保存用户数据
  saveUserData(data) {
    try {
      wx.setStorageSync(this.storageKey, data);
      this.notifyListeners(data);
      return true;
    } catch (e) {
      console.error('保存用户数据失败:', e);
      return false;
    }
  }

  // 更新部分用户数据
  updateUserData(updates) {
    const currentData = this.getUserData();
    const newData = { ...currentData, ...updates };
    return this.saveUserData(newData);
  }

  // 获取默认数据
  getDefaultData() {
    return {
      // 基本信息
      avatar: '/assets/images/default-avatar.jpg',
      name: '',
      signature: '',
      birthday: '',
      gender: '男',
      
      // 身体数据
      height: 170.0,
      weight: 52.0,
      initWeight: 52.0,
      initDate: '',
      targetWeight: 60.0,
      targetDate: '',
      
      // 健康偏好
      preference: '',
      allergy: '',
      special: '',
      medicine: '',
      
      // 健康指标
      healthMetrics: {
        bmi: 0,
        bmiStatus: '正常',
        bodyFatRate: 0, // 体脂率
        bloodPressure: {
          systolic: 0, // 收缩压
          diastolic: 0  // 舒张压
        },
        bloodSugar: {
          fasting: 0,   // 空腹血糖
          postprandial: 0 // 餐后血糖
        },
        lastUpdate: ''
      },
      
      // 体重管理计算数据
      weightData: {
        initial: 52.0,
        current: 52.0,
        target: 60.0,
        gained: 0.0,
        remainingDays: 0,
        initialDate: '',
        targetDate: ''
      },
      
      // 卡路里数据
      calorieData: {
        budget: 1941,
        consumed: 0,
        exercise: 0,
        remaining: 1941
      },
      
      // 记录状态
      recordStatus: {
        weight: { lastUpdate: '7天前', days: 1 },
        water: { lastUpdate: '7天前' },
        jumpRope: { lastUpdate: '今日未记录' }
      }
    };
  }

  // 同步体重数据
  syncWeightData(profileData) {
    const weightData = {
      initial: profileData.initWeight || 52.0,
      current: profileData.weight || 52.0,
      target: profileData.targetWeight || 60.0,
      gained: (profileData.weight || 52.0) - (profileData.initWeight || 52.0),
      remainingDays: 0,
      initialDate: profileData.initDate || '',
      targetDate: profileData.targetDate || ''
    };

    // 计算剩余天数
    if (weightData.initialDate && weightData.targetDate) {
      try {
        const startDate = new Date(weightData.initialDate);
        const endDate = new Date(weightData.targetDate);
        const today = new Date();
        const diffTime = endDate.getTime() - today.getTime();
        weightData.remainingDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      } catch (e) {
        console.error('计算剩余天数失败:', e);
      }
    }

    return weightData;
  }

  // 计算体重管理相关数据
  computeWeightManagement(profileData) {
    const isWeightGain = (profileData.targetWeight || 0) > (profileData.initWeight || 0);
    const weightChangeType = isWeightGain ? '增重' : '减重';
    const delta = Math.abs((profileData.targetWeight || 0) - (profileData.initWeight || 0));
    const weeklyStandard = isWeightGain ? 0.09 : 0.10;
    
    let weeks, weeklyRate;
    
    if (profileData.targetDate && profileData.targetDate !== '') {
      // 用户选择了达成时间，重新计算每周标准
      const startDate = profileData.initDate ? new Date(profileData.initDate) : new Date();
      const endDate = new Date(profileData.targetDate);
      const timeDiff = endDate.getTime() - startDate.getTime();
      const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
      weeks = Math.ceil(daysDiff / 7);
      
      if (weeks > 0) {
        weeklyRate = delta / weeks;
      } else {
        weeks = Math.ceil(delta / weeklyStandard);
        weeklyRate = weeklyStandard;
      }
    } else {
      // 使用默认每周标准计算
      weeks = Math.ceil(delta / weeklyStandard);
      weeklyRate = weeklyStandard;
    }

    return {
      weightChangeType,
      targetWeeks: weeks ? `${weeks}` : '—',
      weeklyRate: weeklyRate ? weeklyRate.toFixed(3) : weeklyStandard.toFixed(3),
      isWeightGain
    };
  }

  // 添加数据变化监听器
  addListener(callback) {
    this.listeners.push(callback);
  }

  // 移除数据变化监听器
  removeListener(callback) {
    const index = this.listeners.indexOf(callback);
    if (index > -1) {
      this.listeners.splice(index, 1);
    }
  }

  // 通知所有监听器
  notifyListeners(data) {
    this.listeners.forEach(callback => {
      try {
        callback(data);
      } catch (e) {
        console.error('数据监听器执行失败:', e);
      }
    });
  }

  // 获取健康页面需要的数据格式
  getHealthPageData() {
    const userData = this.getUserData();
    const weightData = this.syncWeightData(userData);
    const weightManagement = this.computeWeightManagement(userData);
    
    return {
      weightData,
      calorieData: userData.calorieData || {
        budget: 1941,
        consumed: 0,
        exercise: 0,
        remaining: 1941
      },
      recordStatus: userData.recordStatus || {
        weight: { lastUpdate: '7天前', days: 1 },
        water: { lastUpdate: '7天前' },
        jumpRope: { lastUpdate: '今日未记录' }
      },
      ...weightManagement
    };
  }

  // 获取个人信息页面需要的数据格式
  getProfilePageData() {
    const userData = this.getUserData();
    const weightManagement = this.computeWeightManagement(userData);
    
    return {
      form: {
        avatar: userData.avatar || '/assets/images/default-avatar.jpg',
        name: userData.name || '',
        signature: userData.signature || '',
        birthday: userData.birthday || '',
        height: userData.height || 170.0,
        weight: userData.weight || 52.0,
        initWeight: userData.initWeight || 52.0,
        initDate: userData.initDate || '',
        targetWeight: userData.targetWeight || 60.0,
        targetDate: userData.targetDate || '',
        preference: userData.preference || '',
        allergy: userData.allergy || '',
        special: userData.special || '',
        medicine: userData.medicine || ''
      },
      genderIndex: userData.gender === '女' ? 1 : 0,
      specialIndex: this.getSpecialIndex(userData.special),
      medicineIndex: this.getMedicineIndex(userData.medicine),
      ...weightManagement
    };
  }

  // 获取特殊情况索引
  getSpecialIndex(special) {
    const options = ['无','糖尿病','高血压','心脏病','其他'];
    const index = options.indexOf(special || '无');
    return index >= 0 ? index : 0;
  }

  // 获取用药情况索引
  getMedicineIndex(medicine) {
    const options = ['请设置','二甲双胍','格列齐特','其他'];
    const index = options.indexOf(medicine || '请设置');
    return index >= 0 ? index : 0;
  }
}

// 创建单例实例
const userDataManager = new UserDataManager();

module.exports = userDataManager;
